package com.bjh.routing;

import com.bjh.components.ZookUtil;
import com.bjh.model.InterfaceInfo;
import com.bjh.model.ZkNodeData;
import com.bjh.model.ZkProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class Routing {

    @Resource
    private ZookUtil zookUtil;

    @Resource
    private Environment environment;

    ObjectMapper objectMapper = new ObjectMapper();


    public InterfaceInfo loadService(String interfaceName) {
        String nodeData = zookUtil.getNodeData("/" + environment.getProperty("spring.application.name"));
        if(StringUtils.isEmpty(nodeData)) {
            throw new RuntimeException("没有该节点服务");
        }
        try {
            ZkNodeData zkNodeData = objectMapper.readValue(nodeData, ZkNodeData.class);
            List<ZkProperties> zkPropertiesList = zkNodeData.getZkPropertiesList();
            for(ZkProperties zkProperties : zkPropertiesList) {
                if(StringUtils.equals(interfaceName,zkProperties.getInterfaceName())) {
                    List<InterfaceInfo> info = zkProperties.getInfo();
                    return info.get(0);
                }
            }
        } catch (JsonProcessingException e) {
            return null;
        }
        return null;
    }
}
